package com.liuya.safe.controller;

import javax.servlet.http.HttpServlet;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuya.base.BaseController;
import com.liuya.common.StringUtil;
import com.liuya.safe.util.Constants;
import com.liuya.safe.exception.AuthException;
import com.liuya.safe.util.Startup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 重要servlet之一
 */
//@WebServlet(initParams = {},name = "")
public class InitController extends HttpServlet {
    private static final long serialVersionUID = 4879579300062880446L;
    private static final Log log = LogFactory.getLog(InitController.class);

    private Map actionMap; // key/value=url/Action
    private Map actionNameMap; // key/value=url/actionName
    private static boolean secured;
    private static int queryLimit;

    public static boolean isSecured() {
        return secured;
    }

    public static int getQueryLimit() {
        return queryLimit;
    }

    public void init(ServletConfig config) throws ServletException {
//        String path = request.getContextPath();
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

        //设置初始化上下文路径
        BaseController.setBasePath(config.getServletContext().getContextPath());

        super.init(config);
        // start up safe
        startup(config);

    }

    private void startup(ServletConfig config) {
        System.out.println("**** Starting Safe ......");

        String securedStr = config.getInitParameter("secured");
        if (securedStr != null && securedStr.trim().equalsIgnoreCase("false")) {
            secured = false;
            System.out.println("Safe security is disabled. " + "You can enable it in web.xml->SafeController->secured.");
        } else {
            secured = true;
            System.out.println("Safe security is enabled.");
        }

        String queryLimitStr = config.getInitParameter("queryLimit");
        if (!StringUtil.isEmpty(queryLimitStr)) {
            String errorMessage = "Error: queryLimit must be an integer greater than 0!";
            try {
                queryLimit = new Integer(queryLimitStr).intValue();
                Constants.setQueryLimit(queryLimit);
            } catch (NumberFormatException e) {
                System.out.println(errorMessage);
                throw new AuthException(errorMessage, e);
            }

            if (queryLimit <= 0) {
                System.out.println(errorMessage);
                throw new AuthException(errorMessage);
            }

            System.out.println("Safe query limitation is enabled. queryLimit=" + queryLimit);
        } else {
            System.out.println("Safe query limitation is disabled. " + "You can enable it in web.xml->SafeController->queryLimit.");
        }

        String repositoryDir = getServletConfig().getInitParameter("repositoryDir");
        if(repositoryDir == null || repositoryDir.trim().equals(""))
            repositoryDir = getServletContext().getRealPath("/");

//        System.out.println(this.getClass().getClassLoader().getResource("").getPath());
//        System.out.println(this.getClass().getClassLoader().getResource("config/jdbc.properties").getPath());
//        System.out.println(this.getClass().getClassLoader().getResource("config").getPath());
//        String datasourceDir = getServletContext().getRealPath("/WEB-INF/auth/");
        String datasourceDir = getServletConfig().getInitParameter("datasourceDir");
        if(datasourceDir == null || datasourceDir.trim().equals(""))
            datasourceDir = this.getClass().getClassLoader().getResource("config").getPath();
        if (!datasourceDir.endsWith("/") && !datasourceDir.endsWith("\\")) {
//            datasourceDir = datasourceDir + File.separator;
            datasourceDir = datasourceDir + "/";
        }

        //初始化资料库和数据源
        Startup.startup(datasourceDir, repositoryDir);

//        String lineSep = System.getProperty("line.separator");
//        String consoleMsg = "========================================================================================" + lineSep;
//        consoleMsg += "                                                                                       " + lineSep;
//        consoleMsg += "  Safe web console: http://${serverip}:${port}/${context}/Safe/designer.rls    " + lineSep;
//        consoleMsg += "                                                                                       " + lineSep;
//        consoleMsg += "========================================================================================" + lineSep;
//        System.out.println(consoleMsg);

        System.out.println("**** Safe started successfully!");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        if (log.isDebugEnabled()) {
//            log.debug("Get request for " + req.getServletPath());
//        }
//        if (action == null) {
//            if (log.isInfoEnabled()) {
//                log.info("No action matched with: " + req.getServletPath() + ", forward to designer index page");
//            }
//            resp.sendRedirect(req.getContextPath() + "/Safe/designer.rls");
//        } else {
//            action.doGet(req, resp);
//        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        if (log.isDebugEnabled()) {
//            log.debug("Post request for " + req.getServletPath());
//        }
//        if (action == null) {
//            if (log.isInfoEnabled()) {
//                log.info("No action matched with: " + req.getServletPath() + ", forward to designer index page");
//            }
//            resp.sendRedirect(req.getContextPath() + "/Safe/designer.rls");
//        } else {
//            action.doPost(req, resp);
//        }
    }

}